<?php

namespace App\Http\Controllers\Common\TagData\Image;

use App\Http\Controllers\Controller;
use App\Http\Requests\Common\TagData\Image\VimgtagRequest;
use App\Models\Common\TagData\Image\Vimgtag;
use App\Repositories\Common\TagData\Image\VimgtagRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
use Validator;

class VimgtagController extends Controller
{
    use ModelForm;

    /** @var  VimgtagRepository */
    private $vimgtagRepository;

    public function __construct(VimgtagRepository $vimgtagRepo)
    {
        $this->vimgtagRepository = $vimgtagRepo;
    }

    /**
     * Display a listing of the Vimgtag.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('common.tag_data.image.vimgtags.index_header'));
            $content->description(__('common.tag_data.image.vimgtags.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Vimgtag.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('common.tag_data.image.vimgtags.create_header'));
            $content->description(__('common.tag_data.image.vimgtags.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Vimgtag in storage.
     *
     * @param VimgtagRequest $request
     *
     * @return Response
     */
    public function store(VimgtagRequest $request)
    {
        $input = $request->all();

        $vimgtag = $this->vimgtagRepository->create($input);

        Flash::success(__('common.tag_data.image.vimgtags.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('common.tag_data.image.vimgtags.index'));

    }

    /**
     * Display the specified Vimgtag.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $vimgtag = $this->vimgtagRepository->findWithoutFail($id);

        if (empty($vimgtag)) {
            Flash::error(__('common.tag_data.image.vimgtags.not_found'));

            return redirect(route('common.tag_data.image.vimgtags.index'));
        }

        return view('common.tag_data.image.vimgtags.show')->with('vimgtag', $vimgtag);

    }

    /**
     * Show the form for editing the specified Vimgtag.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('common.tag_data.image.vimgtags.edit_header'));
            $content->description(__('common.tag_data.image.vimgtags.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Vimgtag in storage.
     *
     * @param  int              $id
     * @param VimgtagRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $sValidators = [
            'name'       => 'required|max:100',
            'title'      => 'max:100',
            'short_desc' => 'required|max:100',
        ];
        $validators = [];

        $input = $request->all();
        // 判断是否行内编辑
        $input = $this->handleEditable($input);

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }
        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'name'       => '名称',
            'title'      => '标题',
            'short_desc' => '描述',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $vimgtag = $this->vimgtagRepository->findWithoutFail($id);

        if (empty($vimgtag)) {
            Flash::error(__('common.tag_data.image.vimgtags.not_found'));

            return redirect(route('common.tag_data.image.vimgtags.index'));
        }

        $vimgtag = $this->vimgtagRepository->update($input, $id);

        Flash::success(__('common.tag_data.image.vimgtags.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('common.tag_data.image.vimgtags.index'));
    }

    /**
     * Remove the specified Vimgtag from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->vimgtagRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('common.tag_data.image.vimgtags.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $vimgtag = $this->vimgtagRepository->findWithoutFail($id);

        if (empty($vimgtag)) {
            Flash::error(__('common.tag_data.image.vimgtags.not_found'));

            return redirect(route('common.tag_data.image.vimgtags.index'));
        }

        if ($flag = $this->vimgtagRepository->delete($id)) {

            return response()->json(['message' => __('common.tag_data.image.vimgtags.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Vimgtag::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '标签名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->text('short_desc', '描述')->help('必填');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Vimgtag::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // //添加按钮
            // if (!\Gate::check('common.tag_data.image.vimgtags.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('common.tag_data.image.vimgtags.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('common.tag_data.image.vimgtags.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('common.tag_data.image.vimgtags.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('common.tag_data.image.vimgtags.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            //添加按钮
            if (Admin::user()->cannot('common.tag_data.image.vimgtags.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                //编辑按钮
                if (Admin::user()->cannot('common.tag_data.image.vimgtags.edit')) {
                    $actions->disableEdit();
                }
                //删除按钮
                if (Admin::user()->cannot('common.tag_data.image.vimgtags.destroy')) {
                    $actions->disableDelete();
                }
            });

            //导出按钮
            if (Admin::user()->cannot('common.tag_data.image.vimgtags.export')) {
                $grid->disableExport();
            }

            //批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    //批量删除按钮
                    if (Admin::user()->cannot('common.tag_data.image.vimgtags.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '标签名称')->editable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('short_desc', '描述')->editable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
            });
        });
    }
}
